<?php
/**
*
* @package phpBB3
* @version $Id$
* @copyright (c) 2005 phpBB Group
* @license http://opensource.org/licenses/gpl-license.php GNU Public License
*
*/

/**
*/

/**
* @ignore
*/
 
define('IN_PHPBB', true);
$phpbb_root_path = (defined('PHPBB_ROOT_PATH')) ? PHPBB_ROOT_PATH : '../';
$phpEx = substr(strrchr(__FILE__, '.'), 1);
require_once($phpbb_root_path . 'common.' . $phpEx);
require_once($phpbb_root_path . 'includes/functions_display.' . $phpEx);
require_once($phpbb_root_path . 'sv_common.' . $phpEx);
require_once($phpbb_root_path . 'fb/facebook.' . $phpEx);
require_once($phpbb_root_path . 'includes/functions_user.' . $phpEx);

// Start session management
$user->session_begin();
$auth->acl($user->data);
$user->setup('stockvirtual');

$in_fb_iframe = true;

// As we are in FB iframe, check for FB users first. 
// Check if we can get the fb user id.

$signed_request = $_REQUEST["signed_request"];
//echo "<BR>signed_request:" . $signed_request;

// use signed_request, and the following code comes from FB sample: https://developers.facebook.com/docs/appsonfacebook/tutorial/#auth
if($signed_request != '')
{
	list($encoded_sig, $payload) = explode('.', $signed_request, 2); 

	$data = json_decode(base64_decode(strtr($payload, '-_', '+/')), true);
	
    if (empty($data["user_id"])) 
    {
		// if no user data, just leave it.
        //echo("<script> top.location.href='" . $auth_url . "'</script>");
		//echo "empty data";            
    } 
    else 
    {
		//echo ("<BR>Welcome User: " . $data["user_id"]);            
    	// get fb user info.
    	$fb_user_id = $data["user_id"];
    	$token = $data['oauth_token'];    	
    	    	
   		$fb_user_info = file_get_contents("https://graph.facebook.com/$fb_user_id");
		if ($fb_user_info)
		{
			$fb_user = json_decode($fb_user_info,true); // to make it an array  		
						
			// try to login the user
			if (login_fb_user($fb_user['id']) == false)
			{	
				// check if the user name already exist
				if (username_exist($fb_user['name']))
				{				
					$fb_user_info = json_encode ($fb_user);
							
					// redirect to the select name page
					$url = "{$phpbb_root_path}fb/name_conflict.$phpEx?fb_user_info=$fb_user_info";	
					sv_redirect($url);		
				}
					
		  		if (register_fb_user($fb_user['id'], $fb_user['name'], $fb_user['first_name'], $fb_user['last_name'], '', $fb_user['link'], $fb_user['gender'], $fb_user['timezone'], $fb_user['locale'], $fb_user['verified']))
				{
					// refresh
					$url = append_sid("{$phpbb_root_path}fb//index.$phpEx", '');	
					redirect($url, false, true);
					echo "<a href='" . $url . "'>Redirecting...</a><br /><br />" . $url;
				}				
			}
			/*
			else
			{
				// login ok and refresh
				$url = append_sid("{$phpbb_root_path}fb//index.$phpEx", '');	
				redirect($url, false, true);
				echo "<a href='" . $url . "'>Redirecting...</a><br /><br />" . $url;	
			}*/
		}
	} 		
}

		
// update fb access token to session table
if ($token != '')
{
	$sql = 'UPDATE ' . SESSIONS_TABLE . ' 
      					SET fb_access_token="' . $token . '" 
      					WHERE session_id = "' . $db->sql_escape($user->session_id) . '"';
   	$db->sql_query($sql);
}

$show_user_value 	= false;
$show_1_month_roi 	= false;

$money = $user->data['user_money'];
$user_id 	= $user->data['user_id'];

if ($user_id != ANONYMOUS)
{
	// list all holding stock.
	// As we can only show 1 page in FB iframe, provide a url for the user to get detail.	
//	$detail_url	= append_sid("{$phpbb_root_path}index.$phpEx", '');
//	list_holding_stock($query_user_id, 3, htmlentities($detail_url));
	
	// The scroll bar of FB iframe works again, so we don't need to limit on 1 page.
	$r = list_holding_stock($user_id, 0, '', true, true);
	
	$holding_any_stock	= $r['holding_any_stock'];
	$shorting_any_stock = $r['shorting_any_stock'];
	
	// list all open to_buy delegation. 
//	list_open_to_buy_delegation();

	// list all open to_sell delegation. 
//	list_open_to_sell_delegation();
	
	
	// we need to run this before we output page_footer, or this function will not be executed on stockvirtual.info(although it works on localhost).
	// update the user's fb friends. 
//	$user_fb_id = get_user_fb_id($user_id);
//	if ($user_fb_id != 0 && $code != '')
//	{
//		update_fb_friends($user_id, $user_fb_id, $code);	
//	}
}
else
{
	// show ranking directly on index page if the user is not logged in.
	// list highest 20 user values in the latest date. 
	$show_user_value = list_user_value_ranking(10);

	// list highest 20 user ROI in 1 month period. 
	$show_1_month_roi = list_user_roi_ranking(30, 'roi_1_month_list', 10);
}

if (is_newbie($user_id))
{
	$show_welcome_newbie	= true;
	$show_rule 				= true;	
}

// get personal setting
$news_max_number = 10;
$market_info_option = 0;
$result = get_personal_setting($user_id);
if (isset($result))
{
	$news_max_number 	= $result['news_max_number'];
	$market_info_option	= $result['market_info'];
}

// show news
if ($news_max_number != 0)
{
	$show_news = list_news($user_id, $news_max_number);
}

// list all related equity change events.
list_equity_change_event($user_id);

$show_statistics = false;
if ($auth->acl_getf_global('m_'))
{
	$show_statistics = true;	
}

$is_following_anyone = is_following_anyone($user_id);

// Don't show knowledge to save loading time
//$show_knowledge = list_knowledge_titles();
$show_knowledge = false;

// Take 33% chance to show a poll.
if (rand(1 , 3) == 1 && $user_id != ANONYMOUS)
{
	list_poll();
}

display_forums('', $config['load_moderators']);

// Assign index specific vars
$template->assign_vars(array(

	'FORUM_IMG'				=> $user->img('forum_read', 'NO_NEW_POSTS'),
	'FORUM_NEW_IMG'			=> $user->img('forum_unread', 'NEW_POSTS'),
	'FORUM_LOCKED_IMG'		=> $user->img('forum_read_locked', 'NO_NEW_POSTS_LOCKED'),
	'FORUM_NEW_LOCKED_IMG'	=> $user->img('forum_unread_locked', 'NO_NEW_POSTS_LOCKED'),

	'S_LOGIN_ACTION'				=> append_sid("{$phpbb_root_path}ucp.$phpEx", 'mode=login'),
	'S_SV_INDEX'					=> append_sid("{$phpbb_root_path}fb/index.$phpEx", ''),
	'S_BUY_ACTION'					=> append_sid("{$phpbb_root_path}fb/buy.$phpEx", ''),
	'S_SELL_ACTION'					=> append_sid("{$phpbb_root_path}fb/sell.$phpEx", ''),
	'S_SHORT_SELL_ACTION'		=> append_sid("{$phpbb_root_path}fb/short_sell.$phpEx", ''),
	'S_SHORT_COVER_ACTION'		=> append_sid("{$phpbb_root_path}fb/short_cover.$phpEx", ''),
	'S_PERFORMANCE_ACTION'			=> append_sid("{$phpbb_root_path}fb/performance.$phpEx", ''),
	'S_HISTORY_ACTION'				=> append_sid("{$phpbb_root_path}fb/history.$phpEx", ''),
	'S_RANKING_ACTION'				=> append_sid("{$phpbb_root_path}fb/ranking.$phpEx", ''),
	'S_PERSONAL_SETTING_ACTION'		=> append_sid("{$phpbb_root_path}fb/personal_setting.$phpEx", ''),
	'S_RULE'						=> append_sid("{$phpbb_root_path}fb/rule.$phpEx", ''),
	'S_ABOUT'						=> append_sid("{$phpbb_root_path}fb/sv_about.$phpEx", ''),
	'S_FAQ'							=> append_sid("{$phpbb_root_path}fb/sv_faq.$phpEx", ''),
	'S_STATISTICS'					=> append_sid("{$phpbb_root_path}fb/statistics.$phpEx", ''),
	'S_FB_FRIENDS_RANKING_ACTION'	=> append_sid("{$phpbb_root_path}fb/fb_friends_ranking.$phpEx", ''),
	'S_QUERY_USER'					=> append_sid("{$phpbb_root_path}fb/query_user.$phpEx", 'mode=query_user'),
	'S_FOLLOW_INFO'					=> append_sid("{$phpbb_root_path}fb/follow_info.$phpEx", ''),
	'S_DELEGATION_WHILE_SITE'		=> append_sid("{$phpbb_root_path}fb/delegation_whole_site.$phpEx", ''),
	'S_FULL_RANKING'				=> append_sid("{$phpbb_root_path}fb/full_ranking.$phpEx", ''),
	'S_FULL_RANKING_1_MONTH_ROI'	=> append_sid("{$phpbb_root_path}fb/full_ranking.$phpEx", 'mode=1_month_roi'),
	
	
	'S_FB_LOGIN_URL'			=> $loginUrl,
	
	'S_DISPLAY_BIRTHDAY_LIST'	=> ($config['load_birthdays']) ? true : false,

	'S_TO_BUY_DELEGATION_LIST'	=> $to_buy_delegation_list,
	'S_TO_SELL_DELEGATION_LIST'	=> $to_sell_delegation_list,
	'S_EQUITY_CHANGE_EVENT_LIST'=> $equity_change_event_list,
	
	'U_MONEY'					=> number_format($money),
	'U_USERNAME'				=> $user->data['username'],
	
	'S_HIDE_NAV_LINK'				=> true,
	'S_SHOW_RULE'					=> $show_rule,
	'S_SHOW_WELCOME_NEWBIE'			=> $show_welcome_newbie,
	'S_SHOW_STATISTICS'				=> $show_statistics,
	'S_HAS_FB_FRIEND_REGISTERED'	=> true,
	'S_SHOW_KNOWLEDGE'				=> $show_knowledge,
	'S_SHOW_NEWS'					=> $show_news,
	
	'MARKET_INFO_OPTION'			=> $market_info_option,
	
	'S_HOLDING_ANY_STOCK'			=> $holding_any_stock, 
	'S_SHORTING_ANY_STOCK'			=> $shorting_any_stock, 
	
	'U_MARK_FORUMS'		=> ($user->data['is_registered'] || $config['load_anon_lastread']) ? append_sid("{$phpbb_root_path}index.$phpEx", 'hash=' . generate_link_hash('global') . '&amp;mark=forums') : '',
	'U_MCP'				=> ($auth->acl_get('m_') || $auth->acl_getf_global('m_')) ? append_sid("{$phpbb_root_path}mcp.$phpEx", 'i=main&amp;mode=front', true, $user->session_id) : '',
	
	'IN_FB_IFRAME'		=> $in_fb_iframe,
	
	'SHOW_USER_VALUE'	=>	$show_user_value,
	'SHOW_1_MONTH_ROI'	=>	$show_1_month_roi,
	
	'IS_FOLLOWING_ANYONE'	=>	$is_following_anyone,
	
	'S_INCLUDE_JQUERY'				=> true,				// to instruct sv_overall_header.html to include jQuery. 
	'S_INCLUDE_JQUERY_UI'			=> true,				// to instruct sv_overall_header.html to include jQuery UI. 
	
	)
);

// Output page
page_header($user->lang['INDEX']);

$template->set_filenames(array(
	'body' => 'index_body.html')
);

page_footer();
?>